#include "ProtocolHelper.h"

#include <QDataStream>


using namespace Protocol;


QString Helper::commandNameByType(int type)
{
	switch(type)
	{
	case VERSION_REQUEST:
		return "VERSION_REQUEST";
	case VERSION_RESPONSE:
		return "VERSION_RESPONSE";
	case SET_USER_NAME:
		return "SET_USER_NAME";
	case USER_LIST_REQUEST:
		return "USER_LIST_REQUEST";
	case USER_LIST_RESPONSE:
		return "USER_LIST_RESPONSE";

	return "UNKNOWN_COMMAND";
	}
}

QString Helper::deviceStateToString(int state)
{
	switch(state)
	{
	case STATE_IDLE:
		return "ServerStateIdle";

	return "";
	}
}

QString Helper::fromStringStream(QDataStream& readStream)
{

	QString resultString;

	quint16 length;

	readStream >> length;

	for(int i = 0; i < length; ++i)
	{
		quint8 ch;

		readStream >> ch;
		resultString.append(ch);
	}

	return resultString;
}

int Helper::fromEnumStream(QDataStream& readStream)
{
	int size = sizeof(UserState); // UserState выбран для примера
	switch(size){
		case 1:{
			quint8 data;
			readStream >> data;
			return data;
		}
		case 2:{
			quint16 data;
			readStream >> data;
			return data;
		}
		case 4:{
			quint32 data;
			readStream >> data;
			return data;
		}
		case 8:{
			quint64 data;
			readStream >> data;
			return (int)data;
		}
	}
	return -1;
}

QDateTime Helper::dateTimeFromStream(QDataStream& readStream)
{
	QDateTime dt;
	quint8 time_sec;
	quint8 time_min;
	quint8 time_hour;
	quint8 date_day;
	quint8 date_month;
	quint8 date_year;

	readStream >> time_sec >> time_min >> time_hour
			   >> date_day >> date_month >> date_year;

	dt.setTime(QTime(time_hour, time_min, time_sec));
	dt.setDate(QDate(date_year+2000, date_month, date_day));

	return dt;
}

void Helper::stringToDataStream(QDataStream& writeStream, const QString& string)
{
	writeStream << (quint16) string.length();

	for(int i = 0; i < string.length(); ++i)
	{
		writeStream << (quint8) string.at(i).toLatin1();
	}
}

void Helper::dateTimeToDataStream(QDataStream& writeStream, const QDateTime& dateTime)
{
	writeStream
			<< (quint8) dateTime.time().second()
			<< (quint8) dateTime.time().minute()
			<< (quint8) dateTime.time().hour()
			<< (quint8) dateTime.date().day()
			<< (quint8) dateTime.date().month()
			<< (quint8) (dateTime.date().year() % 100);
}

void Helper::enumToDataStream(QDataStream& writeStream, const int& Enum)
{
	int size = sizeof(UserState); // UserState выбран для примера
	switch(size){
		case 1: writeStream << (quint8) Enum; break;
		case 2: writeStream << (quint16) Enum; break;
		case 4: writeStream << (quint32) Enum; break;
		case 8: writeStream << (quint64) Enum; break;
		default: break;
	}
}

QString Helper::commandToHexString(QByteArray& data)
{
	if(data.isEmpty())
		return QString();

	QByteArray cmd = data;
	cmd.remove(1, cmd.length() - 1);
	QByteArray print = data;
	print.remove(0, 1);

	return QString("[cmd %1] [data %2]")
			.arg(QString(cmd.toHex()))
			.arg(print.isEmpty() ? "<empty>": QString(print.toHex()) );
}
